
const apiHost = import.meta.env.VITE_API_HOST || '';
const API_BASE_URL = apiHost+'/prompt';
import { getToken } from '../login/loginApi';

export const getPromptList = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/list`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${getToken()}`
      }
    });
    if (!response.ok) {
      throw new Error('Failed to fetch prompt list');
    }
    return await response.json();
  } catch (error) {
    console.error('Error fetching prompts:', error);
    return [];
  }
};

export const getPromptById = async (id: string) => {
  try {
    const response = await fetch(`${API_BASE_URL}/${id}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${getToken()}`
      }
    });
    if (!response.ok) {
      throw new Error('Failed to fetch prompt by id');
    }
    return await response.json();
  } catch (error) {
    console.error('Error fetching prompt by id:', error);
    return {};
  }
};

export const createPrompt = async (newPrompt: any) => {
  try {
    const response = await fetch(API_BASE_URL, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${getToken()}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(newPrompt)
    });
    if (!response.ok) {
      throw new Error('Failed to create prompt');
    }
    return await response.json();
  } catch (error) {
    console.error('Error creating prompt:', error);
    return {};
  }
};

export const updatePrompt = async (updatedPrompt: any) => {
  try {
    const response = await fetch(API_BASE_URL, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${getToken()}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(updatedPrompt)
    });
    if (!response.ok) {
      throw new Error('Failed to update prompt');
    }
    return await response.json();
  } catch (error) {
    console.error('Error updating prompt:', error);
    return {};
  }
};

export const deletePrompt = async (id: string) => {
  try {
    const response = await fetch(`${API_BASE_URL}/${id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${getToken()}`
      }
    });
    if (!response.ok) {
      throw new Error('Failed to delete prompt');
    }
    return await response.json();
  } catch (error) {
    console.error('Error deleting prompt:', error);
    return {};
  }
};